package com.example.cloud.service.impl;

import com.example.cloud.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件服务实现类
 */
@Service
public class FileServiceImpl implements FileService {
    
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    
    @Value("${file.upload.path:./uploads}")
    private String uploadPath;
    
    @Value("${file.upload.url-prefix:/uploads}")
    private String urlPrefix;
    
    @Value("${file.upload.domain:}")
    private String domain;
    
    @Override
    public Map<String, String> uploadAvatar(MultipartFile file, String oldAvatarUrl) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        
        try {
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 如果有旧头像，尝试删除
            if (oldAvatarUrl != null && !oldAvatarUrl.isEmpty()) {
                deleteFile(oldAvatarUrl);
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            Path filePath = Paths.get(uploadPath, filename);
            Files.write(filePath, file.getBytes());
            
            // 返回文件访问URL（确保包含域名）
            String fileUrl = domain + urlPrefix + "/" + filename;
            
            logger.info("文件上传成功，路径: {}", fileUrl);
            
            Map<String, String> data = new HashMap<>();
            data.put("url", fileUrl);
            
            return data;
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public boolean deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty() || !fileUrl.contains(urlPrefix)) {
            logger.warn("无效的文件URL: {}", fileUrl);
            return false;
        }
        
        try {
            // 从URL中提取文件名
            String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            
            // 构建文件路径
            Path filePath = Paths.get(uploadPath, filename);
            File file = filePath.toFile();
            
            // 检查文件是否存在
            if (!file.exists()) {
                logger.warn("要删除的文件不存在: {}", filePath);
                return true; // 文件不存在也视为删除成功
            }
            
            // 删除文件
            boolean deleted = file.delete();
            if (deleted) {
                logger.info("文件删除成功: {}", filePath);
                return true;
            } else {
                logger.error("文件删除失败: {}", filePath);
                return false;
            }
        } catch (Exception e) {
            logger.error("删除文件失败", e);
            return false;
        }
    }
} 